package com.gzx.spring.boot.utils;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class SpringContext implements ApplicationContextAware {
    private static ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        SpringContext.ctx = ctx;
    }

    public static void initApplicationContext(ApplicationContext ctx) {
        SpringContext.ctx = ctx;
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        if (ctx == null) {
            return null;
        }
        return ctx.getBean(requiredType);
    }

    public static Object getBean(String beanId) {
        if (ctx == null) {
            return null;
        }
        return ctx.getBean(beanId);
    }

    public static Object getBeanNames() {
        if (ctx == null) {
            return null;
        }
        Map<String, Object> beanMap = new HashMap<>();
        for (String name : ctx.getBeanDefinitionNames()) {
            Object bean = ctx.getBean(name);
            if (bean != null) {
                beanMap.put(name, bean.getClass().getName());
            }
        }
        return beanMap;
    }
}
